package com.ruoyi.point.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.point.domain.MallGoods;
import com.ruoyi.point.service.IMallGoodsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 积分商城商品Controller
 * 
 * @author hy
 * @date 2025-08-12
 */
@RestController
@RequestMapping("/point/goods")
public class MallGoodsController extends BaseController
{
    @Autowired
    private IMallGoodsService mallGoodsService;

    /**
     * 查询积分商城商品列表
     */
    @PreAuthorize("@ss.hasPermi('point:mallGoods:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallGoods mallGoods)
    {
        startPage();
        List<MallGoods> list = mallGoodsService.selectMallGoodsList(mallGoods);
        return getDataTable(list);
    }

    /**
     * 导出积分商城商品列表
     */
    @PreAuthorize("@ss.hasPermi('point:mallGoods:export')")
    @Log(title = "积分商城商品", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MallGoods mallGoods)
    {
        List<MallGoods> list = mallGoodsService.selectMallGoodsList(mallGoods);
        ExcelUtil<MallGoods> util = new ExcelUtil<MallGoods>(MallGoods.class);
        return util.exportExcel(list, "积分商城商品数据");
    }

    /**
     * 获取积分商城商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('point:mallGoods:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(mallGoodsService.selectMallGoodsById(id));
    }

    /**
     * 新增积分商城商品
     */
    @PreAuthorize("@ss.hasPermi('point:mallGoods:add')")
    @Log(title = "积分商城商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MallGoods mallGoods)
    {
        return toAjax(mallGoodsService.insertMallGoods(mallGoods));
    }

    /**
     * 修改积分商城商品
     */
    @PreAuthorize("@ss.hasPermi('point:mallGoods:edit')")
    @Log(title = "积分商城商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MallGoods mallGoods)
    {
        return toAjax(mallGoodsService.updateMallGoods(mallGoods));
    }

    /**
     * 删除积分商城商品
     */
    @PreAuthorize("@ss.hasPermi('point:mallGoods:remove')")
    @Log(title = "积分商城商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(mallGoodsService.deleteMallGoodsByIds(ids));
    }

    /**
     * 根据ID查询商品详情（多表联查，包含规格信息）
     */
    @GetMapping("/detail/{id}")
    public AjaxResult getDetail(@PathVariable("id") Integer id)
    {
        try {
            MallGoods goods = mallGoodsService.selectMallGoodsDetailById(id);
            if (goods != null) {
                // 记录查询结果
                System.out.println("商品详情查询成功 - ID: " + id + 
                                 ", 名称: " + goods.getName() + 
                                 ", 规格数量: " + (goods.getSpecifications() != null ? goods.getSpecifications().size() : 0));
                return success(goods);
            } else {
                System.out.println("商品详情查询失败 - ID: " + id + " 未找到");
                return error("商品不存在");
            }
        } catch (Exception e) {
            System.err.println("商品详情查询异常 - ID: " + id + ", 错误: " + e.getMessage());
            e.printStackTrace();
            return error("查询商品详情失败: " + e.getMessage());
        }
    }

    /**
     * 查询商品列表（多表联查，支持分页和筛选）
     */
    @GetMapping("/list-with-stats")
    public TableDataInfo getListWithStats(MallGoods mallGoods)
    {
        startPage();
        List<MallGoods> list = mallGoodsService.selectMallGoodsListWithStats(mallGoods);
        return getDataTable(list);
    }

    /**
     * 查询热门商品列表
     */
    @GetMapping("/hot")
    public AjaxResult getHotList()
    {
        return success(mallGoodsService.selectHotMallGoodsList());
    }

    /**
     * 查询热门商品列表（按销量排序）
     */
    @GetMapping("/hot/sales")
    public AjaxResult getHotListBySales(Integer limit)
    {
        return success(mallGoodsService.selectHotMallGoodsListBySales(limit));
    }

    /**
     * 查询新品列表（按创建时间排序）
     */
    @GetMapping("/new")
    public AjaxResult getNewListByTime(Integer limit)
    {
        return success(mallGoodsService.selectNewMallGoodsListByTime(limit));
    }

    /**
     * 查询推荐商品列表
     */
    @GetMapping("/recommended")
    public AjaxResult getRecommendedList()
    {
        return success(mallGoodsService.selectRecommendedMallGoodsList());
    }

    /**
     * 更新商品库存和销量（兑换后）
     */
    @PostMapping("/update-stock-sales/{goodsId}")
    public AjaxResult updateStockAndSales(@PathVariable("goodsId") Integer goodsId)
    {
        return toAjax(mallGoodsService.updateGoodsStockAndSales(goodsId));
    }
}
